#include "oledip.h"
#include <QHostAddress>
#include <QList>
#include <QNetworkInterface>
OledIP::OledIP(QObject *parent) : QObject(parent)
{
    updataTime  =new QTimer(this);
    connect(updataTime,&QTimer::timeout,this,[=]()
    {
        QString timeStr = QTime::currentTime().toString("    hh:mm:ss    ");
        oled.showString(0,0,timeStr);

        static int timeCount = 9999;
        if(timeCount >= 9999)
        {
            timeCount = 0;
            oled.oledClear();
        }
        if(timeCount % 10 == 0)
        {
            oled.clearLine(1);
            oled.showString(1,0,"temp:" + getCpuTemp());
            oled.clearLine(2);
            oled.showString(2,0,"i p:"+getLocalIp());
            oled.clearLine(3);
            oled.showString(3,0,"mac:"+getMAC());
        }
        timeCount++;
    });
    updataTime->start(1000);
}

QString OledIP::getLocalIp()
{
    QString myIp;
    QList<QHostAddress> ipList = QNetworkInterface::allAddresses();
    for (int i = 0; i < ipList.size(); ++i)	 // 获取第一个本主机的IPv4地址
    {
           if (ipList.at(i) != QHostAddress::LocalHost && ipList.at(i).toIPv4Address())
           {
               myIp= ipList.at(i).toString();
               break;
           }
     }
     if (myIp.isEmpty())	 // 如果没有找到，则使用本地IP
        myIp= QHostAddress(QHostAddress::LocalHost).toString();
     return myIp;
}

QString OledIP::getMAC()
{
    QString myMAC;
    auto interfaces = QNetworkInterface::allInterfaces();

    for (int i = 0; i < interfaces.size(); i++)
    {
        if(interfaces.at(i).name().contains("eth0"))
            if (interfaces.at(i).isValid())
            {
                myMAC= interfaces.at(i).hardwareAddress().replace(":","");
                break;
            }
    }
    return myMAC;
}

#include <QFile>
#define TEMP_PATH "/sys/class/thermal/thermal_zone0/temp"
QString OledIP::getCpuTemp()
{
    char buf[20];
    QFile tempFile(TEMP_PATH);
    if(tempFile.open(QFile::ReadOnly))
    {
        tempFile.read(buf,20);
        float temp = atoi(buf) / 1000.0;
        return QString::number(temp);
    }
    return "";
}
